package org.example.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.request.AlipayOpenAgentCommonSignRequest;
import com.alipay.api.request.AlipayOpenAgentOrderQueryRequest;
import com.alipay.api.response.AlipayOpenAgentCommonSignResponse;
import com.alipay.api.response.AlipayOpenAgentOrderQueryResponse;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.example.config.AlipayConfig;
import org.example.model.dto.MerchantOnboardingRequest;
import org.example.model.dto.MerchantOnboardingResponse;
import org.example.model.dto.QueryOnboardingStatusRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * 商家进件服务类
 * 提供商家入驻申请、状态查询等功能
 *
 * @author zhiyuan
 * @date 2025/10/27
 */
@Slf4j
public class MerchantOnboardingService {

    private final AlipayClient alipayClient;
    private final Gson gson;

    /**
     * 构造方法
     * @param config 支付宝配置
     */
    public MerchantOnboardingService(AlipayConfig config) {
        this.alipayClient = config.createAlipayClient();
        this.gson = new Gson();
    }

    /**
     * 提交商家进件申请
     * 使用 alipay.open.agent.common.sign 接口
     *
     * @param request 商家进件请求参数
     * @return 进件响应结果
     */
    public MerchantOnboardingResponse submitOnboarding(MerchantOnboardingRequest request) {
        try {
            log.info("开始提交商家进件申请，外部业务号：{}", request.getOutBizNo());

            // 构建请求对象
            AlipayOpenAgentCommonSignRequest alipayRequest = new AlipayOpenAgentCommonSignRequest();

            // 构建业务参数
            Map<String, Object> bizContent = buildBizContent(request, alipayRequest);

            alipayRequest.putOtherTextParam("biz_content", gson.toJson(bizContent));

            log.debug("请求参数：{}", gson.toJson(bizContent));

            // 发起API调用
            AlipayOpenAgentCommonSignResponse response = alipayClient.execute(alipayRequest);

            log.info("支付宝返回结果 - code: {}, msg: {}, subCode: {}, subMsg: {}",
                    response.getCode(), response.getMsg(),
                    response.getSubCode(), response.getSubMsg());

            // 处理响应
            if (response.isSuccess()) {
                log.info("商家进件申请提交成功，申请单号：{}", response.getBody());
                MerchantOnboardingResponse result = MerchantOnboardingResponse.success(
                    response.getBody(),
                    request.getOutBizNo()
                );
                return result;
            } else {
                log.error("商家进件申请失败 - subCode: {}, subMsg: {}",
                        response.getSubCode(), response.getSubMsg());
                return MerchantOnboardingResponse.failure(
                    response.getCode(),
                    response.getMsg(),
                    response.getSubCode(),
                    response.getSubMsg()
                );
            }

        } catch (Exception e) {
            log.error("提交商家进件申请异常", e);
            return MerchantOnboardingResponse.failure(
                "SYSTEM_ERROR",
                "系统异常",
                "EXCEPTION",
                e.getMessage()
            );
        }
    }

    /**
     * 查询商家进件状态
     * 使用 alipay.open.agent.order.query 接口
     *
     * @param request 查询请求
     * @return 进件响应结果
     */
    public MerchantOnboardingResponse queryOnboardingStatus(QueryOnboardingStatusRequest request) {
        try {
            log.info("开始查询商家进件状态，申请单号：{}", request.getApplyId());

            // 构建请求对象
            AlipayOpenAgentOrderQueryRequest alipayRequest = new AlipayOpenAgentOrderQueryRequest();

            // 构建业务参数
            Map<String, String> bizContent = new HashMap<>();
            if (request.getApplyId() != null) {
                bizContent.put("order_id", request.getApplyId());
            }
            if (request.getOutBizNo() != null) {
                bizContent.put("out_biz_no", request.getOutBizNo());
            }

            alipayRequest.setBizContent(gson.toJson(bizContent));

            // 发起API调用
            AlipayOpenAgentOrderQueryResponse response = alipayClient.execute(alipayRequest);

            log.info("支付宝返回结果 - code: {}, msg: {}", response.getCode(), response.getMsg());

            // 处理响应
            if (response.isSuccess()) {
                MerchantOnboardingResponse result = new MerchantOnboardingResponse();
                result.setSuccess(true);
                result.setCode(response.getCode());
                result.setMsg(response.getMsg());
                result.setApplyId(response.getBody());
                result.setAuditStatus(response.getOrderStatus());
                result.setMerchantPid(response.getMerchantPid());

                log.info("查询成功 - 状态：{}, 商户PID：{}",
                        response.getOrderStatus(), response.getMerchantPid());

                return result;
            } else {
                log.error("查询进件状态失败 - subCode: {}, subMsg: {}",
                        response.getSubCode(), response.getSubMsg());
                return MerchantOnboardingResponse.failure(
                    response.getCode(),
                    response.getMsg(),
                    response.getSubCode(),
                    response.getSubMsg()
                );
            }

        } catch (Exception e) {
            log.error("查询商家进件状态异常", e);
            return MerchantOnboardingResponse.failure(
                "SYSTEM_ERROR",
                "系统异常",
                "EXCEPTION",
                e.getMessage()
            );
        }
    }

    /**
     * 构建进件业务参数
     */
    private Map<String, Object> buildBizContent(MerchantOnboardingRequest request, AlipayOpenAgentCommonSignRequest signRequest) {
        Map<String, Object> bizContent = new HashMap<>();


        // 基本信息
        bizContent.put("out_biz_no", request.getOutBizNo());

        // 商户信息
        Map<String, String> merchantInfo = new HashMap<>();
        merchantInfo.put("name", request.getMerchantName());
        merchantInfo.put("alias_name", request.getMerchantShortName());
        merchantInfo.put("merchant_type", request.getMerchantType());

        if (request.getBusinessLicense() != null) {
            merchantInfo.put("license_no", request.getBusinessLicense());
        }

        bizContent.put("merchant_info", merchantInfo);

        // 法人信息
        if (request.getLegalPersonName() != null) {
            Map<String, String> legalPerson = new HashMap<>();
            legalPerson.put("name", request.getLegalPersonName());
            legalPerson.put("cert_type", request.getLegalPersonCertType());
            legalPerson.put("cert_no", request.getLegalPersonCertNo());
            bizContent.put("legal_person_info", legalPerson);
        }

        // 联系人信息
        if (request.getContactName() != null) {
            Map<String, String> contact = new HashMap<>();
            contact.put("name", request.getContactName());
            contact.put("mobile", request.getContactMobile());
            if (request.getContactEmail() != null) {
                contact.put("email", request.getContactEmail());
            }
            bizContent.put("contact_info", contact);
        }

        // 经营地址
        if (request.getAddress() != null) {
            Map<String, String> address = new HashMap<>();
            address.put("province", request.getProvince());
            address.put("city", request.getCity());
            address.put("district", request.getDistrict());
            address.put("address", request.getAddress());
            bizContent.put("address_info", address);
        }

        // 结算账户信息
        if (request.getAccountNo() != null) {
            Map<String, String> account = new HashMap<>();
            account.put("account_name", request.getAccountName());
            account.put("account_no", request.getAccountNo());
            account.put("bank_name", request.getBankName());
            if (request.getBankBranchName() != null) {
                account.put("bank_branch_name", request.getBankBranchName());
            }
            if (request.getBankProvince() != null) {
                account.put("bank_province", request.getBankProvince());
                account.put("bank_city", request.getBankCity());
            }
            bizContent.put("account_info", account);
        }

        // 经营类目
        if (request.getMccCode() != null) {
            bizContent.put("mcc_code", request.getMccCode());
        }

        return bizContent;
    }
}
